package com.salmon.oss.server;

import com.salmon.oss.service.OssHandlerServiceImpl;
import com.salmon.thrift.OssHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TFastFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TNonblockingServerTransport;

@Slf4j
public class ThriftApiServer {

    private OssHandlerServiceImpl ossHandlerService;

    private int port = 8888;

    public ThriftApiServer(OssHandlerServiceImpl ossHandlerService){
        this.ossHandlerService = ossHandlerService;
    }

    public ThriftApiServer(OssHandlerServiceImpl ossHandlerService, int port){
        this.ossHandlerService = ossHandlerService;
        this.port = port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * NIO 方式， 效率高
     */
    public void start() {
        OssHandlerService.Processor processor = new OssHandlerService.Processor<>(ossHandlerService);
        try {
            TNonblockingServerTransport transport = new TNonblockingServerSocket(port);
            TThreadedSelectorServer.Args tArgs =  new TThreadedSelectorServer.Args(transport);
            tArgs.processor(processor);
            //tArgs.transportFactory(new TFramedTransport.Factory());
            tArgs.transportFactory(new TFastFramedTransport.Factory());
            //二进制协议
            tArgs.protocolFactory(new TBinaryProtocol.Factory());
            TServer server = new TThreadedSelectorServer(tArgs);
            log.info("thrift服务启动成功, 端口={}", port);
            server.serve();
        } catch (Exception e) {
            log.error("thrift服务启动失败", e);
        }
    }
}
